import {getOrderDetail, orderCancel, orderPay} from '../../api/order.js';
import Util from '../../utils/util.js';
import {getContentList} from "../../api/api";
import Status from "../../utils/status";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dialogTip: false,
    order_id: null,
    order: {},
    lists: [],

    fields: {
      menu_title: {title: "菜单",},
      create_time: {title: "下单时间",},
      out_trade_no: {title: "订单号"},
      amount: {title: "数量", unit: "x", dc: "fnum"},
      total_price: {title: "订单总额", unit: "￥"},
      current_status: {title: "订单状态"},
      deliver_time: {title: "配送时间"},
    },

    statusList: {
      1: "待付款",
      10: "进行中",
      11: "待接单",
      12: "出餐中",
      20: "已完成",

      21: "取餐中",
      22: "待配送",
      23: "配送中",
      24: "已送达",

      60: "已退款",
      80: "已取消",
    },

    helpList: [
      {title: "餐品有质量问题"},
      {title: "订单什么时候送到"},
      {title: "缺餐品"},
      {title: "如何申请退款"},
    ],

    reasonList: [],

    reasonIndex: '',

    btnActive: true,
    cancelDialog: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    const that = this;
    this.data.order_id = options.order_id || '';

    wx.showLoading({
      title: "正在加载..."
    })
    Util.chekWxLogin().then(res => {
      that.setData({
        userInfo: res.userInfo,
        reasonList: Status.reasonList(),
      })
      wx.hideLoading()
    }).then(() => {
      getOrderDetail(this.data.order_id).then(res => {
        wx.hideLoading();

        let order = res.data.order;
        let current_status = order.current_status || order.status;
        let fields = that.data.fields

        fields['current_status'].default_val = that.data.statusList[current_status] || '';
        that.setData({fields: fields})
        that.setData({current_status: current_status})
        that.setData(res.data)

        if (!Util.isEmpty(order) && order.status == 1) {
          that.countTime();
        }

      }).catch(errmsg => {
        Util.Tips({
          title: errmsg
        }, {
          tab: 1,
          url: "../order/index"
        })
      })

      getContentList({category_id: 12, limit: 4}).then(res => {
        that.setData({
          helpList: res.data.items || [],
        });
      })

      this.onLoadTabbar();
    }).catch(errmsg => {
      wx.hideLoading()
    })
  },

  // 跳转到搜索
  countTime() {
    const that = this
    let order = that.data.order;
    if (Util.isEmpty(order) || order.status != 1 || Util.isEmpty(order.end_time))
      return;

    //设置截止时间
    let days, hours, minutes, seconds,
      nowDate = order.end_time || '',
      now = new Date().getTime(),
      end = new Date(nowDate.replace(/-/g, "/")).getTime();

    if (!nowDate)
      return;

    let leftTime = end - now; //时间差
    if (leftTime >= 0) {
      days = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      hours = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      minutes = Math.floor(leftTime / 1000 / 60 % 60);
      seconds = Math.floor(leftTime / 1000 % 60);
      seconds = seconds < 10 ? "0" + seconds : seconds
      minutes = minutes < 10 ? "0" + minutes : minutes
      hours = hours < 10 ? "0" + hours : hours
      that.setData({
        countdown: hours + ":" + minutes + ":" + seconds,
        days,
        hours,
        minutes,
        seconds
      })

      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 1000);
    } else {
      order.current_status = order.status = 80
      orderCancel(order.out_trade_no, '', 'countdown');//取消

      that.setData({
        countdown: '已截止',
        order: order,
      })

    }
  },

  confirmTip(e) {
    const that = this;
    let order = this.data.order,
      fields = this.data.fields

    if (this.data.reasonIndex.length === 0) {
      Util.Tips({title: "请选择取消原因", hideMask: true});
      return;
    }
    if (!this.data.btnActive)
      return false;

    this.setData({
      btnActive: false
    })
    wx.showLoading({title: "正在取消..."})
    orderCancel(this.data.order_id, this.data.reasonList[this.data.reasonIndex]).then(res => {
      order.current_status = order.status = (order.status == 1 ? 80 : 60)
      fields['current_status']['default_val'] = that.data.statusList[order.status];
      that.setData({
        fields: fields,
        order: order,
        cancelDialog: false,
        current_status: order.status,
      })
      Util.Tips({title: res.msg || "取消成功", hideMask: true})
    }).catch(errmsg => {
      Util.Tips({title: errmsg})
    }).finally(() => {
      that.setData({
        btnActive: true
      })
    })
  },

  closeCancelDialog(e) {
    this.setData({
      cancelDialog: false
    })
  },

  showDialog(e) {
    this.setData({
      cancelDialog: true
    })
  },

  radioChange(e) {
    this.setData({
      reasonIndex: e.detail.value
    })
  },

  makePhoneCall(e) {
    const mobile = e.currentTarget.dataset.mobile;
    Util.callPhone(mobile)
  },

  copyTxt: function (e) {
    wx.setClipboardData({
      data: this.data.order.out_trade_no + '',
      success: function (res) {
        return Util.Tips({title: "复制成功", hideMask: true})
      }
    })
  },

  updateOrderTap: function (e) {
    let _this = this;
    let order_id = _this.data.order_id;
    let dataType = e.currentTarget.dataset.type;

    let tip = {
      1: '确认取消订单？',
      2: '确认收到商品？',
    };

    wx.showModal({
      title: "提示",
      content: tip[dataType],
      success: function (o) {
        if (o.confirm) {
          App._post_form('Order/update', {
            order_id: order_id,
            dataType: dataType
          }, function (result) {
            _this.getOrderDetail(order_id);
          });
        }
      }
    });

  },

  goBack(e) {//返回
    let pages = getCurrentPages()

    if (pages.length > 1) {
      wx.navigateBack()
    } else {
      wx.switchTab({
        url: "../member/index"
      })
    }
  },

  /**
   * 发起付款
   */
  payOrder: function (e) {
    const that = this;
    let order = that.data.order,
      fields = that.data.fields,
      current_status = that.data.current_status;

    // order.status = 11;
    order.current_status = order.status = 11;
    current_status = 11;
    fields['current_status'].default_val = that.data.statusList[current_status] || '';
    wx.showLoading({title: '正在支付...',});
    orderPay({order_id: order.out_trade_no})
      .then(res => {
        let data = res.data
        if (!Util.isEmpty(data.status) && data.status === 10) {
          that.setData({
            order: order,
            fields: fields,
            current_status: current_status,
          })
          return;
        }

        wx.requestPayment({
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': 'MD5',
          'paySign': data.paySign,
          success: function (res) {
            wx.setStorageSync('is_refresh', 1)
            that.setData({
              order: order,
              fields: fields,
              current_status: current_status,
            })

            return app.Tips({title: "付款成功", icon: "success"})
          },
          fail: function (res) {
            return app.Tips({title: "取消支付成功"})
          }
        })
      }).catch(errmsg => {
      Util.Tips({title: errmsg})
    })
  },

  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this

    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})

      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          if (!rect) return;
          let bottom = parseInt(rect.height);
          if (that.data.isIphoneX) {
            bottom += 24;
          } else {
            bottom += 15;
          }
          that.setData({
            bottom: bottom
          })
        }).exec()
    });
  },

});